package com.topcent.tioxyc.xxljob;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.YY1_KPI;
import com.topcent.tioxyc.pojo.cc.MaterialVOCC;
import com.topcent.tioxyc.pojo.vo.*;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/4/9 09:02
 * @Description: 销售订单数据-YY1_KPI and 交货单数据入简道云
 */
@Slf4j
@Component
public class SalesDataOfYY1_KPIXxlJob {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    @XxlJob("SalesDataOfYY1_KPI")
    public void execute() {
        Header[] headers = ConnmeUtils.createHeaders();
        String appId = "67f8aa2676b9b3942c49035f";
        String entryId = "67f8aa6d945a5abcaab9369e";

        // 获取物料-大类
        // 固定物料大类：编码 -> 名称
        Map<String, String> materialMapZ = new HashMap<>();
        materialMapZ.put("Z101", "基础五金");
        materialMapZ.put("Z102", "收纳五金");
        materialMapZ.put("Z103", "功能五金");
        materialMapZ.put("Z104", "装潢五金"); // 修正“装潢五余”为“装潢五金”（推测笔误）
        materialMapZ.put("Z105", "配件");
        materialMapZ.put("Z106", "包材");

        String appIdMaterial = "668c9750508d1d2bf336211a";
        String entryIdMaterial = "668c98146b86173be43e6a21";
        List<MaterialVOCC> materialVOCCList = ConnmeUtils.getJianDaoYunData(headers, appIdMaterial, entryIdMaterial, MaterialVOCC.class);

        Map<String, String> materialMap = new HashMap<>();
        for (MaterialVOCC vo : materialVOCCList) {
            String originalCode = vo.get_widget_1720490004612(); // 物料编码
            String newCode = vo.get_widget_1720490004647(); // Z101
            if (StringUtils.isNotBlank(originalCode) && StringUtils.isNotBlank(newCode) ) {
                materialMap.put(originalCode, materialMapZ.get(newCode));
            }
        }
        // 物料分类
        Map<String, String> bToXHMap = materialVOCCList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1721371578612() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(MaterialVOCC::get_widget_1720490004612, MaterialVOCC::get_widget_1721371578612, (v1, v2) -> v1)); // key重复取第一个

        // 获取用户人员信息
        Map<String ,Object> person =new HashMap<>();
        person.put("dept_no", 1);
        person.put("has_child", true);
        JSONObject personResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/user/list", headers, JSONUtil.toJsonStr(person));
        String personData = personResult.getStr("users");
        JSONArray personObjects = JSONUtil.parseArray(personData);
        List<Assignee> personList = JSONUtil.toList(personObjects, Assignee.class);

        // 获取销售部门信息
        Map<String ,Object> cond =new HashMap<>();
        cond.put("dept_no", 1);
        cond.put("has_child", true);
        JSONObject deptResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/list", headers, JSONUtil.toJsonStr(cond));
        String data = deptResult.getStr("departments");
        JSONArray objects = JSONUtil.parseArray(data);
        List<DepartmentVO> deptList = JSONUtil.toList(objects, DepartmentVO.class);

        Map<String, String> userNameMap = personList.stream()
                .collect(Collectors.toMap(Assignee::getName, Assignee::getUsername, (v1, v2) -> v1));

        Map<String, Integer> deptMap = deptList.stream()
                .collect(Collectors.toMap(DepartmentVO::getName, DepartmentVO::getDept_no, (v1, v2) -> v1));

        // Java 8 中使用传统流式操作替代 flatMapping 和 nullsLast
        Map<String, DateTime> salesDocMinDateMap = this.getSalesOrderList().stream()
                .filter(so -> so.getReview_date() != null) // 过滤空日期
                .collect(Collectors.toMap(
                        SalesOrder::get_widget_1718759603973, // 键：销售单号
                        SalesOrder::getReview_date,   // 值：日期
                        BinaryOperator.minBy(Comparator.naturalOrder()) // 冲突时保留较小的日期
                ));

        //客户建档日期
        Map<String, Date> customerList = getCustomerList();
        List<YY1_KPI> yy1KpiList = yy1KpiMapper.selectAll();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (YY1_KPI yy1Kpi : yy1KpiList){
            SalesDataYY1 vo = new SalesDataYY1();
            vo.set_widget_1762495647054(yy1Kpi.getYY1_Brand_SDI());
            vo.set_widget_1743998205163(getYearMonth(yy1Kpi.getYY1_lastapptime_SDH()));
            vo.set_widget_1743997558327(yy1Kpi.getSalesDocument()); vo.set_widget_1744784769246(yy1Kpi.getSalesDocument());vo.set_widget_1743997558328(yy1Kpi.getSalesDocumentItem()); vo.set_widget_1743997558329(yy1Kpi.getSoldToParty());
            vo.set_widget_1743997558330(yy1Kpi.getCustomerName()); vo.set_widget_1743997558331(yy1Kpi.getBusinessPartnerName1()); vo.set_widget_1744099905120(yy1Kpi.getAuthorizationGroupText());vo.set_widget_1751677806926(yy1Kpi.getAuthorizationGroupText());
            vo.set_widget_1743997558333(yy1Kpi.getCompanyCodeName()); vo.set_widget_1743997558335(yy1Kpi.getPurchaseOrderByCustomer());
            vo.set_widget_1743997558336(yy1Kpi.getMaterial()); vo.set_widget_1743997558337(yy1Kpi.getSalesDocumentItemText()); vo.set_widget_1743997558338(yy1Kpi.getQuantity());
            vo.set_widget_1743997558339(yy1Kpi.getNetAmount()); vo.set_widget_1743997558340(yy1Kpi.getOrderQuantityUnit()); vo.set_widget_1743997558341(yy1Kpi.getConditionAmount());
            vo.set_widget_1743997558342(yy1Kpi.getExchangeRate_a()); vo.set_widget_1743997558343(yy1Kpi.getGroupCurrency()); vo.set_widget_1743997558344(convertToISO8601Format(yy1Kpi.getYY1_lachangedatetime1_SDH()));
            vo.set_widget_1743997558345(yy1Kpi.getID()); vo.set_widget_1743997558346(yy1Kpi.getSalesDocApprovalStatusDesc()); vo.set_widget_1743997558347(yy1Kpi.getAddressSearchTerm2());
            vo.set_widget_1743997558348(convertToISO8601Format(yy1Kpi.getCreationDate())); vo.set_widget_1743997558349(yy1Kpi.getOverallTotalDeliveryStatus()); vo.set_widget_1743997558350(yy1Kpi.getOverallDeliveryStatus());
            vo.set_widget_1743997558351(yy1Kpi.getPlant()); vo.set_widget_1743997558352(yy1Kpi.getCurrency()); vo.set_widget_1743997558353(yy1Kpi.getExchangeRate_b());
            vo.set_widget_1743997558354(yy1Kpi.getNetAmount_1()); vo.set_widget_1743997558355(yy1Kpi.getConditionAmount1()); vo.set_widget_1743997558356(yy1Kpi.getConditionCurrency());

            vo.set_widget_1743997558357(yy1Kpi.getGsjing()); vo.set_widget_1743997558358(yy1Kpi.getGshan()); vo.set_widget_1743997558359(convertToISO8601Format(yy1Kpi.getYY1_lastapptime_SDH()));
            vo.set_widget_1743997558360(yy1Kpi.getYY1_ZBMCL_SD_SDI()); vo.set_widget_1743997558361(yy1Kpi.getYY1_ZCL_SD_SDI()); vo.set_widget_1743997558362(yy1Kpi.getYY1_ZGGCC_SD_SDI());
            vo.set_widget_1743997558363(yy1Kpi.getYY1_ZBZXX_SD_SDI()); vo.set_widget_1743997558364(yy1Kpi.getYY1_KS_SD_SDI()); vo.set_widget_1743997558365(yy1Kpi.getYY1_ZCPJZ_SD_SDI());
            vo.set_widget_1743997558366(yy1Kpi.getYY1_ZPJ_SD_SDI()); vo.set_widget_1743997558367(yy1Kpi.getVCDescription()); vo.set_widget_1743997558368(yy1Kpi.getYY1_BGPM_PRD());
            vo.set_widget_1743997558369(yy1Kpi.getYY1_Brand_SDI()); vo.set_widget_1743997558370(yy1Kpi.getCountryName()); vo.set_widget_1743997558371(yy1Kpi.getYY1_khly_bus());
            vo.set_widget_1743997558372(yy1Kpi.getBusinessPartnerGroupingText()); vo.set_widget_1743997558373(convertToISO8601Format(yy1Kpi.getRequestedDeliveryDate()));
            vo.set_widget_1763017757219(materialMap.get(yy1Kpi.getMaterial())); // 物料大类
            vo.set_widget_1763090533407(materialMap.get(yy1Kpi.getMaterial())); // 物料类型

            vo.set_widget_1749538106589(salesDocMinDateMap.get(yy1Kpi.getSalesDocument()));// 最早审核时间
            vo.set_widget_1749628279931(customerList.get(yy1Kpi.getSoldToParty()));//客户建档日期
            if(StringUtils.isNotBlank(yy1Kpi.getSalesOfficeName()) && yy1Kpi.getSalesOfficeName().contains("中非销售")){
                yy1Kpi.setSalesOfficeName("BCP中非销售部");
            }else if(StringUtils.isNotBlank(yy1Kpi.getSalesOfficeName()) && yy1Kpi.getSalesOfficeName().contains("东南亚销售")){
                yy1Kpi.setSalesOfficeName("BCP东南亚销售部");
            }else if(StringUtils.isNotBlank(yy1Kpi.getSalesOfficeName()) && yy1Kpi.getSalesOfficeName().contains("DIY销售部")){
                yy1Kpi.setSalesOfficeName("BCP美澳销售部");
            }
            String sName = yy1Kpi.getSalesOfficeName();
            vo.set_widget_1751677806927(sName);

            String username = userNameMap.get(vo.get_widget_1744099905120());
            if(("刘晓琪").equals(vo.get_widget_1744099905120())){
                username = "woxjrqDwAAUDe1Gd9cSVXI5sfRaqZ9jQ";
            }
            if (username != null) {
                vo.set_widget_1744099905120(username);
            }

            Integer deptNo = deptMap.get(sName);
            if (deptNo != null) {
                vo.set_widget_1744094850882(deptNo);
            }

            vo.set_id(null);
            mapList.add(ConnmeUtils.convertEntityToMap(vo));

        }
        //批量删除简道云数据
        selectAndList(headers);

        // 批量存入简道云
        int batchSize = 100;
        for (int i = 0; i < mapList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, mapList.size());
            List<Map<String, Object>> batchDataIds = mapList.subList(i, endIndex);
            // 存入简道云
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", appId);
            parameter.put("entry_id", entryId);
            parameter.put("data_list", batchDataIds);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/batch_create", headers, jsonSale);
        }
        log.info("销售订单数据-YY1_KPI：==== {}", yy1KpiList.size());
        // 交货单数据入简道云
        deliveryDocumentsData();
    }

    public void selectAndList(Header[] headers){
        // 获取到销售订单数据-YY1_KPI数据。
        List<Lin> consolidatedOrderVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "67f8aa2676b9b3942c49035f");
        parameter.put("entry_id", "67f8aa6d945a5abcaab9369e");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "_widget_1744599627176");
        cond.put("type", "text");
        cond.put("method", "empty");
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Lin> list = JSONUtil.toList(objects, Lin.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            consolidatedOrderVOList.addAll(list);
        } while (fale);
        log.info("销售订单数据-YY1_KPI表单数据size：" + consolidatedOrderVOList.size());
        // 判断集合是否有值 有则删除 一次只能删除100条
        if (CollectionUtils.isNotEmpty(consolidatedOrderVOList)) {
            // 提取所有数据ID
            List<String> dataIds = consolidatedOrderVOList.stream()
                    .map(Lin::get_id) // get_id() 是获取数据ID的方法
                    .collect(Collectors.toList());

            int batchSize = 100;
            for (int i = 0; i < dataIds.size(); i += batchSize) {
                int endIndex = Math.min(i + batchSize, dataIds.size());
                List<String> batchDataIds = dataIds.subList(i, endIndex);

                // 构造删除接口请求参数
                Map<String, Object> deleteParam = new HashMap<>();
                deleteParam.put("app_id", "67f8aa2676b9b3942c49035f");
                deleteParam.put("entry_id", "67f8aa6d945a5abcaab9369e");
                deleteParam.put("data_ids", batchDataIds);

                // 发送删除请求
                String jsonDelete = JSONUtil.toJsonStr(deleteParam);
                JSONObject deleteResponse = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/batch_delete", headers, jsonDelete);
                // 记录响应日志,判断删除是否成功
                //log.info("删除接口响应：{}", deleteResponse);
            }
        }
    }
    // 时间Z转化
    public static String convertToISO8601Format(String dbTime) {
        if(StringUtils.isEmpty(dbTime)){
            return "";
        }
        // 查找秒后的小数部分
        int dotIndex = dbTime.indexOf(".");

        if (dotIndex != -1) {
            // 如果有小数部分，去掉并加上 ".000"
            dbTime = dbTime.substring(0, dotIndex) + ".000";
        } else {
            // 如果没有小数部分，直接加 ".000"
            dbTime = dbTime + ".000";
        }
        // 定义数据库时间格式
        DateTimeFormatter dbFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

        // 解析数据库时间
        LocalDateTime localDateTime = LocalDateTime.parse(dbTime, dbFormatter);

        // 将时间减去 8 小时
        LocalDateTime result = localDateTime.minusHours(8);

        // 将结果转换为字符串输出
        return result.format(dbFormatter);
    }

    // 取年月
    public static String getYearMonth(String dbTime) {
        if (dbTime == null || dbTime.isEmpty()) {
            return null;
        }
        // 查找秒后的小数部分
        int dotIndex = dbTime.indexOf(".");

        if (dotIndex != -1) {
            // 如果有小数部分，去掉并加上 ".000"
            dbTime = dbTime.substring(0, dotIndex) + ".000";
        } else {
            // 如果没有小数部分，直接加 ".000"
            dbTime = dbTime + ".000";
        }

        // 定义数据库时间格式
        DateTimeFormatter dbFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        LocalDateTime localDateTime = LocalDateTime.parse(dbTime, dbFormatter);

        // 将时间减去 8 小时
        LocalDateTime result = localDateTime.minusHours(8);

        // 获取年份和月份
        return result.format(DateTimeFormatter.ofPattern("yyyy-MM"));
    }

    // 交货单数据-简道云
    public void deliveryDocumentsData() {
        String appId = "67f8aa2676b9b3942c49035f";
        String entryId = "67f8aa542669a40210bc7655";
        Header[] headers = ConnmeUtils.createHeaders();
        // 获取用户人员信息
        Map<String ,Object> person =new HashMap<>();
        person.put("dept_no", 1);
        person.put("has_child", true);
        JSONObject personResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/user/list", headers, JSONUtil.toJsonStr(person));
        String personData = personResult.getStr("users");
        JSONArray personObjects = JSONUtil.parseArray(personData);
        List<Assignee> personList = JSONUtil.toList(personObjects, Assignee.class);
        Map<String, String> userNameMap = personList.stream()
                .collect(Collectors.toMap(Assignee::getName, Assignee::getUsername, (v1, v2) -> v1));
        // 获取销售部门信息
        Map<String ,Object> cond =new HashMap<>();
        cond.put("dept_no", 1);
        cond.put("has_child", true);
        JSONObject deptResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/list", headers, JSONUtil.toJsonStr(cond));
        String data = deptResult.getStr("departments");
        JSONArray objects = JSONUtil.parseArray(data);
        List<DepartmentVO> deptList = JSONUtil.toList(objects, DepartmentVO.class);
        Map<String, Integer> deptMap = deptList.stream()
                .collect(Collectors.toMap(DepartmentVO::getName, DepartmentVO::getDept_no, (v1, v2) -> v1));
        // 获取原始数据
        List<DeliveryDocumentsEntity> originalData = yy1KpiMapper.selecDeliveryDocumentsDatatAll();
        // 创建新集合存放处理后的数据
        List<DeliveryDocumentsEntity> processedData = new ArrayList<>();

        // 用于记录已出现的 a|b|c 组合
        Set<String> seenKeys = new HashSet<>();

        for (DeliveryDocumentsEntity doc : originalData) {
            // 假设字段名为 a、b、c，请根据你实体类实际字段名调整
            String key = doc.getReferenceSDDocumentItem() + "|" + doc.getReferenceSDDocument() + "|" + doc.getDeliveryDocument();

            if (seenKeys.add(key)) { // 如果这个组合是第一次出现，就添加
                processedData.add(doc);
            }
        }

        // 获取 销售-物料 数据
        List<YY1_KPI> orderMList = yy1KpiMapper.selectOrderM();

        // 初始化Map，键为 "SalesDocument-Material"，值为 YY1_Brand_SDI
        Map<String, Boolean> salesMaterialToBrandMap = orderMList.stream()
                .collect(Collectors.toMap(
                        // 键生成逻辑：SalesDocument-Material（处理空值）
                        kpi -> {
                            String salesDocument = kpi.getSalesDocument() == null ? "" : kpi.getSalesDocument();
                            String material = kpi.getMaterial() == null ? "" : kpi.getMaterial();
                            return salesDocument + "-" + material;
                        },
                        // 值生成逻辑：YY1_Brand_SDI（null 时保留 null）
                        YY1_KPI::getYY1_Brand_SDI,
                        // 键重复时的处理：保留后面的值（与原代码 put 覆盖逻辑一致）
                        (existingValue, newValue) -> newValue
                ));

        // 获取物料-大类
        // 固定物料大类：编码 -> 名称
        Map<String, String> materialMapZ = new HashMap<>();
        materialMapZ.put("Z101", "基础五金");
        materialMapZ.put("Z102", "收纳五金");
        materialMapZ.put("Z103", "功能五金");
        materialMapZ.put("Z104", "装潢五金"); // 修正“装潢五余”为“装潢五金”（推测笔误）
        materialMapZ.put("Z105", "配件");
        materialMapZ.put("Z106", "包材");

        String appIdMaterial = "668c9750508d1d2bf336211a";
        String entryIdMaterial = "668c98146b86173be43e6a21";
        List<MaterialVOCC> materialVOCCList = ConnmeUtils.getJianDaoYunData(headers, appIdMaterial, entryIdMaterial, MaterialVOCC.class);

        Map<String, String> materialMap = new HashMap<>();
        for (MaterialVOCC vo : materialVOCCList) {
            String originalCode = vo.get_widget_1720490004612(); // 物料编码
            String newCode = vo.get_widget_1720490004647(); // Z101
            if (StringUtils.isNotBlank(originalCode) && StringUtils.isNotBlank(newCode) ) {
                materialMap.put(originalCode, materialMapZ.get(newCode));
            }
        }

        // 物料分类
        Map<String, String> bToFLMap = materialVOCCList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1720490004631() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(MaterialVOCC::get_widget_1720490004612, MaterialVOCC::get_widget_1720490004631, (v1, v2) -> v1)); // key重复取第一个

        // 物料型号
        Map<String, String> bToXHMap = materialVOCCList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1721371578612() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(MaterialVOCC::get_widget_1720490004612, MaterialVOCC::get_widget_1721371578612, (v1, v2) -> v1)); // key重复取第一个

        //客户主数据集合
        List<Customer> customerList = getCustomerList1();
        // 物料集合
        List<Wuliao01VO> wuliao01VOList = selectList();
        // 1. 将 wuliao01VOList 先转换为 Map，以 b 字段为 key，c 字段为 value，提高查找效率
        Map<String, String> bToCMap = wuliao01VOList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1720490004614() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Wuliao01VO::get_widget_1720490004612, Wuliao01VO::get_widget_1720490004614, (v1, v2) -> v1)); // key重复取第一个

        //建档日期
        Map<String, Date> bToTimeMap = customerList.stream()
                .filter(customer ->
                        customer.get_widget_1722305048887() != null && // 过滤键为null
                                customer.get_widget_1733204191654() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Customer::get_widget_1722305048887, Customer::get_widget_1733204191654, (v1, v2) -> v1)); // key重复取第一个

        // 国家名称
        Map<String, String> bToCountryMap = customerList.stream()
                .filter(customer ->
                        customer.get_widget_1722305048887() != null && // 过滤键为null
                                customer.get_widget_1722233514707() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Customer::get_widget_1722305048887, Customer::get_widget_1722233514707, (v1, v2) -> v1)); // key重复取第一个
        // 客户来源
        Map<String, String> bToFromMap = customerList.stream()
                .filter(customer ->
                        customer.get_widget_1722305048887() != null && // 过滤键为null
                                customer.get_widget_1722217596689() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Customer::get_widget_1722305048887, Customer::get_widget_1722233514707, (v1, v2) -> v1)); // key重复取第一个

        List<Map<String, Object>> mapList = new ArrayList<>();
        // 将处理后的数据存入简道云
        for (DeliveryDocumentsEntity entity : originalData) {
            DeliveryDocumentVO vo = new DeliveryDocumentVO();
            vo.set_widget_1744266564406(entity.getDeliveryDocument());vo.set_widget_1744266564407(entity.getDeliveryDocumentItem());vo.set_widget_1744609087389(entity.getReferenceSDDocument());vo.set_widget_1744784800889(entity.getReferenceSDDocument());vo.set_widget_1744266564409(entity.getReferenceSDDocumentItem());vo.set_widget_1744266564410(entity.getReferenceSDDocumentCategory());
            vo.set_widget_1744266564411(entity.getOverallGoodsMovementStatus());vo.set_widget_1744266564412(entity.getLastChangeDateTime());vo.set_widget_1744266564413(entity.getDeliveryDocumentType());vo.set_widget_1744266564414(entity.getCreationDate());vo.set_widget_1744266564415(entity.getDocumentDate());
            vo.set_widget_1744266564416(entity.getActualGoodsMovementDate());vo.set_widget_1744266564417(entity.getPlannedGoodsIssueDate());vo.set_widget_1744266564418(entity.getSoldToParty());vo.set_widget_1744266564419(entity.getAddressSearchTerm1());vo.set_widget_1744600670161(entity.getYY1_divison_seller_DLH());vo.set_widget_1751677327160(entity.getYY1_divison_seller_DLH());
            vo.set_widget_1744266564421(entity.getSalesOffice());vo.set_widget_1744266564422(entity.getSalesGroup());vo.set_widget_1744266564423(entity.getStorageLocation());vo.set_widget_1744266564424(entity.getYY1_IF_Release_WMS_DLH());vo.set_widget_1744266564425(entity.getYY1_If_Company_Sales_DLI());
            vo.set_widget_1744266564426(entity.getYY1_XXDDBZ_TT_DLH());vo.set_widget_1744266564427(entity.getYY1_XSDDBZ_DLI());
            vo.set_widget_1744266564428(entity.getProduct());vo.set_widget_1744266564429(entity.getBatch());vo.set_widget_1744266564430(entity.getYY1_ZBZXX_SD_DLI());vo.set_widget_1744266564431(entity.getYY1_DeliveryPlant_DLI());
            vo.set_widget_1744266564432(entity.getYY1_ZBMCL_SD_DLI());vo.set_widget_1744266564433(entity.getYY1_ZCL_SD_DLI());vo.set_widget_1744266564434(entity.getYY1_ZGGCC_SD_DLI());vo.set_widget_1744266564435(entity.getYY1_ZCPJZ_SD_DLI());vo.set_widget_1744266564436(entity.getYY1_KS_SD_DLI());
            vo.set_widget_1744266564437(entity.getYY1_ZPJ_SD_DLI());vo.set_widget_1744266564438(entity.getMaterialGroup());vo.set_widget_1744266564439(entity.getYY1_ifvcmaterial_DLI());vo.set_widget_1744266564440(entity.getYY1_WMS_Material_Name_DLI());vo.set_widget_1744266564441(entity.getVcDescription());
            vo.set_widget_1744266564442(entity.getPlant());vo.set_widget_1744266564443(entity.getActualDeliveryQuantity());
            vo.set_widget_1744266564444(entity.getDeliveryQuantityUnit());vo.set_widget_1744266564445(entity.getExchangeRate_a());vo.set_widget_1744266564446(entity.getGroupCurrency());
            vo.set_widget_1744266564447(entity.getExchangeRate_b());vo.set_widget_1744266564448(entity.getCompanyCodeCurrency());vo.set_widget_1744266564449(entity.getConditionRateValue1());vo.set_widget_1744266564450(entity.getNetPriceAmount1());
            vo.set_widget_1744266564451(entity.getNetPriceQuantity());vo.set_widget_1744266564452(entity.getConditionCurrency());vo.set_widget_1744266564453(entity.getNetPriceQuantityUnit());vo.set_widget_1744266564454(entity.getAmount1());
            vo.set_widget_1744266564455(entity.getNetAmount1());vo.set_widget_1744266564456(entity.getAmount2());vo.set_widget_1744266564457(entity.getNetAmount2());vo.set_widget_1744266564458(entity.getAmount3());vo.set_widget_1744266564459(entity.getNetAmount3());
            vo.set_widget_1744266564461(entity.getPlantName());vo.set_widget_1744266564462(entity.getId());vo.set_widget_1744266564463(entity.getBusinessPartnerName1());vo.set_widget_1744266564464(entity.getAddressSearchTerm2());
            vo.set_widget_1744266564465(entity.getCreationDate_1());vo.set_widget_1744266564466(entity.getBusinessPartnerGrouping());vo.set_widget_1744266564467(entity.getYY1_khly_bus());vo.set_widget_1744266564468(entity.getRegion());vo.set_widget_1744266564469(entity.getVcDescription_1());
            vo.set_widget_1763021802059(bToFromMap.get(entity.getSoldToParty())); // 客户来源
            vo.set_widget_1763021802058(materialMap.get(entity.getProduct())); // 物料大类
            vo.set_widget_1763021802057(bToFLMap.get(entity.getProduct())); // 物料分类
            vo.set_widget_1763088136385(salesMaterialToBrandMap.get(entity.getReferenceSDDocument() +"-"+ entity.getProduct())); // 是否自主品牌
            vo.set_widget_1763088937593(bToXHMap.get(entity.getProduct())); // 物料型号

            vo.set_widget_1749632989516(bToCMap.get(entity.getProduct()));
            vo.set_widget_1749632989517(bToTimeMap.get(entity.getSoldToParty()));vo.set_widget_1749632989518(bToCountryMap.get(entity.getSoldToParty()));

            // 1. 创建表示"2025-06-30"的日期对象（精确到当天结束，即23:59:59.999）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 与字段的timezone保持一致
            Date cutoffDate = null;
            try {
                cutoffDate = sdf.parse("2025-06-30T23:59:59.999Z");
            } catch (ParseException e) {
                e.printStackTrace(); // 处理日期解析异常
            }
            if(entity.getActualGoodsMovementDate() != null && entity.getActualGoodsMovementDate().after(cutoffDate)){
                if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("中非销售")){
                    entity.setSalesOfficeName("BCP中非销售部");
                }else if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("东南亚销售")){
                    entity.setSalesOfficeName("BCP东南亚销售部");
                }else if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("DIY销售部")){
                    entity.setSalesOfficeName("BCP美澳销售部");
                }else if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("PRO国内销售部")){
                    entity.setSalesOfficeName("PRO亚非销售部");
                }
            }

            // 定义需要特殊处理的a值集合
            Set<String> specialCodes = new HashSet<>(Arrays.asList(
                    "80006813", "80006811", "80006812",
                    "80006809", "80006810", "80006805",
                    "80006808", "80006804", "80005937"
            ));

            String sName = entity.getSalesOfficeName();
            // 判断a是否在特殊值集合中，如果是则设置为BCP东南亚销售部
            if (specialCodes.contains(vo.get_widget_1744266564406())) {
                sName = "BCP东南亚销售部";
            }
            vo.set_widget_1744266564460(sName);
            String username = userNameMap.get(vo.get_widget_1744600670161());
            if(("刘晓琪").equals(vo.get_widget_1744600670161())){
                username = "woxjrqDwAAUDe1Gd9cSVXI5sfRaqZ9jQ";
            }
            if (username != null) {
                vo.set_widget_1744600670161(username);
            }

            Integer deptNo = deptMap.get(sName);
            if (deptNo != null) {
                vo.set_widget_1745292386442(deptNo);
            }

            vo.set_id(null);
            mapList.add(ConnmeUtils.convertEntityToMap(vo));

        }

        //批量删除简道云数据
        ConnmeUtils.selectAndDeleteList(headers, appId, entryId, "_widget_1744600670162");

        int batchSize = 100;
        for (int i = 0; i < mapList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, mapList.size());
            List<Map<String, Object>> batchDataIds = mapList.subList(i, endIndex);
            // 存入简道云
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", appId);
            parameter.put("entry_id", entryId);
            parameter.put("data_list", batchDataIds);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/batch_create", headers, jsonSale);
        }
    }
    public List<SalesOrder> getSalesOrderList(){
        List<SalesOrder> salesOrderList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            salesOrderList.addAll(list);
        } while (fale);
        return salesOrderList;
    }

    public Map<String, Date> getCustomerList(){
        Map<String, Date> customerMap = new HashMap<>();
        List<Customer> customerList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a6f42ff97af74b02d217df");
        parameter.put("entry_id", "66a6f443333584e2c128154f");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Customer> list = JSONUtil.toList(objects, Customer.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            customerList.addAll(list);
        } while (fale);

        // 转换 List<Customer> 为 Map<String, Date>
        for (Customer customer : customerList) {
            String customerCode = customer.get_widget_1722305048887();
            Date createDate = customer.get_widget_1733204191654();

            // 处理空值（跳过无效数据）
            if (customerCode != null && createDate != null) {
                customerMap.put(customerCode, createDate);
            }
        }
        return customerMap;
    }

    public List<Customer> getCustomerList1(){
        List<Customer> customerList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a6f42ff97af74b02d217df");
        parameter.put("entry_id", "66a6f443333584e2c128154f");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Customer> list = JSONUtil.toList(objects, Customer.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            customerList.addAll(list);
        } while (fale);
        return customerList;
    }

    // 获取物料主数据
    public List<Wuliao01VO> selectList(){
        Header[] headers = ConnmeUtils.createHeaders();
        // 获取到产品主数据数据。
        List<Wuliao01VO> consolidatedOrderVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "668c9750508d1d2bf336211a");
        parameter.put("entry_id", "668c98146b86173be43e6a21");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Wuliao01VO> list = JSONUtil.toList(objects, Wuliao01VO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            consolidatedOrderVOList.addAll(list);
        } while (fale);
        log.info("产品主数据表单数据size：" + consolidatedOrderVOList.size());
        return consolidatedOrderVOList;
    }
}
